<?php
namespace Home\Controller;

use My\Model\DistributionShopRateModel;
use Utuo\DistributionShopForeground;
use My\Model\DistributionShopOrderModel;

/**
 * 对交易的所有商品评价
 * @author song
 */
class DisShopRateController extends DistributionShopForeground {
	
	// 初始化
	public function _init() {
		layout('disshop');
		$this->setModelName('DistributionShop');
		$this->setModelControllerName("DisShop");
	}
	
	/**
	 * 评价
	 */
	public function rateAction() {
		$this->checkLogin();
		$orderId = I('order_id');
		$productOrder = D( "My/DistributionShopOrder" )->getOrder($orderId);
		$this->assign("productOrder", $productOrder);
		$this->display("{$this->modelControllerName}/" . ACTION_NAME );
	}
	
	/**
	 * 买家评价提交
	 *   格式:
	 * 		'order_id' => '订单id',
	 * 		'rates' => array('order_goods_id(订单商品编号)' => array(
	 *						 'content' => '评价内容',
	 *						),... ...);
	 */
	public function ratePostAction() {
		$this->checkLogin();
		$orderId = I('order_id') or $this->ajaxError('未知订单号');
		$rates = I('rates', array()) or $this->ajaxError('评论内容不能为空');
		$order =  D( "My/DistributionShopOrder" )->getOrder($orderId);
		$order or $this->ajaxError("未找到订单");
		/* 购买方式的附加处理 */
		if ( $order['buy_method'] == DistributionShopOrderModel::BUY_METHOD_GIFTS ) {
			$order['to_uid'] == $this->uid or $this->ajaxError("未找到订单");
		} else {
			$order['uid'] == $this->uid or $this->ajaxError("未找到订单");
		}
		false === D("My/DistributionShopRate")->submitRate($order, $rates, $this->uid) and $this->ajaxSuccess("评价失败");
		$this->ajaxSuccess("评价成功");
	}
	
	// 更多商品评价
	public function moreRateAction() {
		$productId = I("product_id", 0);
		$condition = array(
			'rate.product_id' => $productId,
			'rate.reviewer' => DistributionShopRateModel::REVIEWER_BUYER,
			'rate.status' => DistributionShopRateModel::RATE_CHECK_PASS,
		);
		$list = $this->lists($condition, "id desc",true, $this->getPageSize(), $this->getPage());
		$totalPages = ceil($list['count'] / $this->getPageSize()); //总页数
		// 显示更多评价数据
		$data = array();
		if($this->getPage() <= $totalPages) {
			$data = $list['data'];
		}
		$this->ajaxSuccess('', $data);
	}
	
	// 商品评价列表
	private function lists($condition, $order = "", $paginate = false, $pageSize = 10, $p = 1) {
		$m = M("DistributionShopRate rate")->join("__DISTRIBUTION_SHOP_ORDER_GOODS__ goods on rate.order_goods_id = goods.id", "LEFT")
								  ->join("__WECHAT_USER__ user on rate.uid = user.id", "LEFT")
								  ->field("goods.*,rate.content,rate.create_time,user.nickname as userNickName")->where($condition);
		$new_m = clone $m;
		// 分页处理
		if($paginate) {
			$m->limit($this->getPageSize())->page($this->getPage());
			$contentCount = $new_m->count();
		}
		$contentLists = $m->order($order)->select();
		return array('count' => $contentCount, 'data' => $contentLists);
	}
	
}